<template>
  <div class="p-4">
    <el-button type="primary" @click="openDialog()">新增部门</el-button>

    <el-table :data="departmentList" border class="mt-4" style="width: 100%">
      <el-table-column prop="deptId" label="编号" width="80" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="leader" label="负责人" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDepartment(scope.row.deptId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="form.deptId ? '编辑部门' : '新增部门'" v-model="dialogVisible">
      <el-form label-width="80px" :model="form">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="form.leader" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm()">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const departmentList = ref([])
const dialogVisible = ref(false)
const form = ref({})

const loadData = async () => {
  const res = await axios.get('/departments')
  departmentList.value = res.data.data
}

const openDialog = (row = {}) => {
  form.value = { ...row }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (form.value.deptId) {
    await axios.put('/departments', form.value)
  } else {
    await axios.post('/departments', form.value)
  }
  dialogVisible.value = false
  ElMessage.success('保存成功')
  loadData()
}

const deleteDepartment = (id) => {
  ElMessageBox.confirm('确认删除该部门？', '提示').then(async () => {
    await axios.delete(`/departments/${id}`)
    ElMessage.success('删除成功')
    loadData()
  })
}

onMounted(() => loadData())
</script>
